﻿using WebApi.Extensions;
using WebApi.Infrastructure;

namespace WebApi;

public static class DependencyInjection
{
    public static IServiceCollection AddPresentation(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddEndpointsApiExplorer();
        
        services.AddApiVersioningInternal();
        
        services.AddSwaggerGenInternal();
        
        services.AddRateLimiting();
        
        services.AddCorsInternal(configuration);
        
        services.AddExceptionHandler<GlobalExceptionHandler>();
        
        // 配置 ProblemDetails
        services.AddProblemDetails(options =>
        {
            // 自定义 ProblemDetails 的行为
            options.CustomizeProblemDetails = context =>
            {
                // 添加 traceId 用于追踪
                context.ProblemDetails.Extensions["traceId"] = context.HttpContext.TraceIdentifier;
                
                // 添加实例路径
                context.ProblemDetails.Instance = context.HttpContext.Request.Path;
                
                // 开发环境显示更多信息
                if (context.HttpContext.RequestServices.GetRequiredService<IHostEnvironment>().IsDevelopment())
                {
                    context.ProblemDetails.Extensions["timestamp"] = DateTime.UtcNow;
                }
            };
        });
        
        return services;
    }
}
